package com.nhncorp.pleiades.persistence;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.Serializable;

import com.nhncorp.pleiades.hadoop.Writable;
import com.nhncorp.pleiades.hadoop.WritableUtils;
import com.nhncorp.pleiades.protocol.ClientLockInfo;

public class LockStatus implements Serializable, Writable {

  private static final long serialVersionUID = 1L;
  private String hostName;
  private String lockId;
  private int mode;
  private long lastCommitTime;
  private byte[] metaData;
  
  public LockStatus() {
    this("", "", 0);
  }  
  public LockStatus(String name, String id, int mode) {
    this(name, id, mode, null);
  }  
  
  public LockStatus(String name, String id, int mode, byte[] metaData) {
    this.lockId = id;
    this.hostName = name;
    this.mode = mode;
    this.lastCommitTime = System.currentTimeMillis();
    this.metaData = metaData;
  }
  
  public String getHostName() {
    return hostName;
  }
  public void setHostName(String hostName) {
    this.hostName = hostName;
  }
  public long getLastCommitTime() {
    return lastCommitTime;
  }
  public void setLastCommitTime(long lastCommitTime) {
    this.lastCommitTime = lastCommitTime;
  }
  public String getLockId() {
    return lockId;
  }
  public void setLockId(String lockId) {
    this.lockId = lockId;
  }
  public int getMode() {
    return mode;
  }
  public void setMode(int mode) {
    this.mode = mode;
  }  
  
  public boolean equals(Object obj) {
    if( !(obj instanceof LockStatus) )  return false;
    
    LockStatus otherLockStatus = (LockStatus)obj;
    return lockId.equals(otherLockStatus.lockId);
  }
  
  
  public int hashCode() {
    return lockId.hashCode();
  }
  
  public String toString() {
    return lockId + "," + hostName + "," + mode + "," + lastCommitTime;
  }
  
  public void readFields(DataInput in) throws IOException {
    this.hostName = WritableUtils.readString(in);
    this.lockId = WritableUtils.readString(in);
    this.mode = in.readInt();
    this.lastCommitTime = in.readLong();
    int length = in.readInt();
    if(length > 0) {
      if(length > ClientLockInfo.MAX_META) {
        throw new IOException("Too big meta value:" + length);
      }
      metaData = new byte[length];
      in.readFully(metaData);
    }    
  }
  
  public void write(DataOutput out) throws IOException {
    WritableUtils.writeString(out, hostName);
    WritableUtils.writeString(out, lockId);
    out.writeInt(mode);
    out.writeLong(lastCommitTime);
    
    int length = 0;
    if(metaData != null) {
      length = metaData.length;
    }
    out.writeInt(length);
    if(length > 0) {
      out.write(metaData);
    }
  }
  
  public byte[] getMetaData() {
    return metaData;
  }
  public void setMetaData(byte[] metaData) {
    this.metaData = metaData;
  }
}
